package tju.mic.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Snow
 */
public class SecurityUtils {

    public static String getTicketSeq() {
        return UUID.randomUUID().toString();
    }

    public static String hashPassword(String password) {
        try {
            if (password == null) {
                return null;
            }
            password = "salt1924a79f8" + password; // this is not salt, Salt stops 2 user passwords from being the same, i.e. the userId.
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(password.getBytes(), 0, password.length());
            return new BigInteger(1, digest.digest()).toString(16).toUpperCase();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SecurityUtils.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * 检查密码强度
     *
     * @param password
     * @return
     */
    public static int checkPasswordStrength(String password) {
        int strengthPercentage = 0;
        String[] partialRegexChecks = {".*[a-z]+.*", // lower
            ".*[A-Z]+.*", // upper
            ".*[\\d]+.*", // digits
            ".*[@#$%]+.*" // symbols
    };
        if (password.matches(partialRegexChecks[0])) {
            strengthPercentage += 20;
        }
        if (password.matches(partialRegexChecks[1])) {
            strengthPercentage += 20;
        }
        if (password.matches(partialRegexChecks[2])) {
            strengthPercentage += 20;
        }
        if (password.matches(partialRegexChecks[3])) {
            strengthPercentage += 20;
        }
        if (password.length()>=8){
            strengthPercentage += 20;
        }else{
            if (strengthPercentage>50){
                strengthPercentage = 50;
            }
        }
        return strengthPercentage;
    }
}
